package com.cool.reggie.modules.dish.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cool.reggie.core.redis.RedisKey;
import com.cool.reggie.core.redis.RedisUtils;
import com.cool.reggie.modules.category.entity.CategoryEntity;
import com.cool.reggie.modules.category.service.CategoryService;
import com.cool.reggie.modules.dish.dto.DishDto;
import com.cool.reggie.modules.dish.entity.DishEntity;
import com.cool.reggie.modules.dish.service.DishService;
import com.cool.reggie.modules.dish.vo.DishVo;
import com.cool.reggie.modules.dishFlavor.entity.DishFlavorEntity;
import com.cool.reggie.modules.dishFlavor.service.DishFlavorService;
import com.cool.reggie.utils.ResultData;
import com.cool.reggie.utils.SpringContextUtils;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import net.sf.cglib.beans.BeanCopier;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.util.ReflectionUtils;
import org.springframework.web.bind.annotation.*;

import java.lang.reflect.Method;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 菜品管理 前端控制器
 * </p>
 *
 * @author 1950735817@qq.com
 * @since 2022-07-06
 */
@RestController
@RequestMapping("/dish")
@Slf4j
public class DishController {
    @Autowired
    private DishService dishService;

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private DishFlavorService dishFlavorService;

    @Autowired
    private RedisUtils redisUtils;


    @GetMapping("/page")
    public ResultData list(int page, int pageSize, String name) {
        Page<DishEntity> pageInfo = new Page<>();
        Page<DishDto> dishDtoPage = new Page<>();
        pageInfo.setCurrent(page);
        pageInfo.setSize(pageSize);

        LambdaQueryWrapper<DishEntity> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(StringUtils.isNotBlank(name), DishEntity::getName, name);
        queryWrapper.orderByDesc(DishEntity::getSort);

        Page<DishEntity> pageResult = dishService.page(pageInfo, queryWrapper);

        BeanUtils.copyProperties(pageInfo, dishDtoPage, "records");

        List<DishDto> list = pageResult.getRecords().stream().map((item) -> {
            DishDto dishDto = new DishDto();

            BeanUtils.copyProperties(item, dishDto);

            Long categoryId = dishDto.getCategoryId();

            CategoryEntity category = categoryService.getById(categoryId);

            if (category != null) {
                dishDto.setCategoryName(category.getName());
            }


            return dishDto;
        }).collect(Collectors.toList());

        dishDtoPage.setRecords(list);

        return ResultData.ok(dishDtoPage);
    }

//    @Cacheable(value="dishCache",key="#id",condition = "#result!=null")
    @GetMapping("{id}")
    public ResultData queryDishInfo(@PathVariable("id") Long id) {
        DishDto dishDto = dishService.getByIdWithFlavor(id);
        return ResultData.ok(dishDto);
    }

    @CacheEvict(value="dishCache",key="#dishDto.id")
    @PutMapping
    public ResultData updateDishInfo(@RequestBody DishDto dishDto) {

        dishService.updateWithFlavor(dishDto);

        redisUtils.deleteByPattern(RedisKey.getDishKey(dishDto.getCategoryId().toString()));
        return ResultData.ok();
    }

    @CachePut(value="dishCache",key="#dishDto.id")
    @PostMapping
    public ResultData save(@RequestBody DishDto dishDto) {
        dishService.saveWithFlavor(dishDto);
        return ResultData.ok();
    }

    @GetMapping("/list")
    public ResultData selectListByCategoryId(DishEntity dishEntity) {

        // 从缓存中查询是否存在
        List<DishDto> redisList = (List<DishDto>)redisUtils.get(RedisKey.getDishKey(dishEntity.getCategoryId().toString()), List.class);

        if(redisList!=null){
            return ResultData.ok(redisList);
        }
        // 已上架套餐
        LambdaQueryWrapper<DishEntity> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(DishEntity::getStatus, 1);
        queryWrapper.eq(DishEntity::getCategoryId, dishEntity.getCategoryId());
        queryWrapper.orderByDesc(DishEntity::getSort).orderByDesc(DishEntity::getUpdateTime);
        List<DishEntity> list = dishService.list(queryWrapper);



        List<DishDto> listDto = list.stream().map((item) -> {
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(item, dishDto);

            Long categoryId = item.getCategoryId();

            CategoryEntity category = categoryService.getById(categoryId);
            if (category != null) {
                String categoryName = category.getName();
                dishDto.setCategoryName(categoryName);
            }

            Long dishId = item.getId();

            LambdaQueryWrapper<DishFlavorEntity> query = new LambdaQueryWrapper<>();
            // 已上架套餐
            query.eq(DishFlavorEntity::getDishId, dishId);
            List<DishFlavorEntity> flavorEntities = dishFlavorService.list(query);
            dishDto.setFlavors(flavorEntities);

            return dishDto;
        }).collect(Collectors.toList());

        // 如果redis中不存在，那么存入数据
        redisUtils.set(RedisKey.getDishKey(dishEntity.getCategoryId().toString()),listDto);
        return ResultData.ok(listDto);
    }

}
